package com.zhongli.devplatform.component.qq;

import cn.hutool.core.lang.Assert;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhongli.devplatform.component.qq.QQClientConfig;
import com.zhongli.devplatform.security.qq.QQAccessToken;
import com.zhongli.devplatform.security.qq.QQUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * qq相关工具类
 * @author WuXiCheng
 * @version 1.0
 * @date 2020/8/18 14:45
 */
@Component
@Slf4j
public class QQAuthUtil {

    /**
     * 获取用户信息url
     */
    //private final static String USER_INFO_URL = "https://graph.qq.com/user/get_user_info?access_token=%s&oauth_consumer_key=%s&openid=%s";
    private final static String USER_INFO_URL = "https://graph.qq.com/user/get_simple_userinfo?access_token=%s&oauth_consumer_key=%s&openid=%s";

    private final QQClientConfig clientConfig;

    private final RestTemplate restTemplate;

    @Autowired
    public QQAuthUtil(QQClientConfig clientConfig, RestTemplate restTemplate) {
        this.clientConfig = clientConfig;
        this.restTemplate = restTemplate;
    }

    /**
     * 获取QQ授权后的基本信息
     * @param accessToken
     * @param openId
     * @return
     */
    public QQUserInfo getUserInfo(String accessToken, String openId) {
        String url = String.format(USER_INFO_URL,accessToken,clientConfig.getAppId(),openId);
        //RestTemplate template = new RestTemplate();
        //String userInfoResult = template.getForObject(url, String.class);
        String userInfoResult = restTemplate.getForObject(url, String.class);
        QQUserInfo qqUserInfo = jsonToObject(userInfoResult, QQUserInfo.class);
        return qqUserInfo;
    }

    /**
     * 获取accessToken
     * @param accessTokenURL
     * @return
     */
    public QQAccessToken getToken(String accessTokenURL) {
        Assert.notNull(accessTokenURL,"accessTokenURL不能为空");
        //RestTemplate template = new RestTemplate();
        //发送请求获取accessToken
        //String[] results = template.getForObject(accessTokenURL, String.class).split("&");
        String[] results = Objects.requireNonNull(restTemplate.getForObject(accessTokenURL, String.class)).split("&");
        if (results.length == 3){
            QQAccessToken qqAccessToken = new QQAccessToken();
            String accessToken = results[0].replace("access_token=", "");
            int expiresIn = Integer.valueOf(results[1].replace("expires_in=", ""));
            String refreshToken = results[2].replace("refresh_token=", "");
            qqAccessToken.setAccessToken(accessToken);
            qqAccessToken.setExpiresIn(expiresIn);
            qqAccessToken.setRefresh_token(refreshToken);
            return qqAccessToken;
        }
        return null;
    }

    /**
     * 获取openId
     * @param accessToken
     * @return
     */
    public String getOpenId(String accessToken){
        String url = clientConfig.getOpenIdUri() + accessToken;
        //RestTemplate template = new RestTemplate();
        //发送请求获取openId
        //String openIdResult = template.getForObject(String.format(url,accessToken), String.class);
        String openIdResult = restTemplate.getForObject(String.format(url,accessToken), String.class);
        Pattern pattern = Pattern.compile("\"openid\":\"(.*?)\"");
        assert openIdResult != null;
        Matcher matcher = pattern.matcher(openIdResult);
        if (matcher.find()){
            return matcher.group(1);
        }
        return null;
    }

    /**
     * json字符串传对象
     * @param json
     * @param targetClass
     * @param <T>
     * @return
     */
    private <T> T jsonToObject(String json,Class<T> targetClass){
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        try {
            return objectMapper.readValue(json,targetClass);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
